package com.cjbdi.util;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;

/**
 * 实体类型转换的工具类
 */

public class CopyUtil {

    /**
     * 类型转换：实体模型<->实体
     * <p>
     * 例如：List<DataModel> <--> List<Data>
     */

    public static <T> List<T> copyList(List list, Class<T> target) {
        List<T> newList = new ArrayList<>();
        for (Object entity : list) {
            newList.add(copy(entity, target));
        }
        return newList;
    }

    /**
     * 类型转换：实体模型 <->实体
     * <p>
     * 例如：DataModel <--> Data
     */
    public static <T> T copy(Object origin, Class<T> target) {
        T t = null;
        try {
            t = target.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        BeanUtils.copyProperties(origin, t);
        return t;
    }
}